<template>
  <div class="image-upload-demo">
    <el-card header="图片上传功能演示">
      <div class="mb-4">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :auto-upload="false"
          :limit="3"
          :on-change="handleFileChange"
          accept="image/*"
          multiple
        >
          <el-button type="primary" :loading="uploading"> 选择图片上传 </el-button>
          <template #tip>
            <div class="el-upload__tip">支持 jpg/png/gif 格式，单个文件不超过5MB</div>
          </template>
        </el-upload>
      </div>

      <div v-if="uploadedImages.length > 0">
        <el-divider>已上传的图片</el-divider>
        <div class="image-grid">
          <div v-for="image in uploadedImages" :key="image.filename" class="image-item">
            <el-image :src="image.url" :preview-src-list="[image.url]" class="uploaded-image" />
            <div class="image-info">
              <el-text size="small">{{ image.filename }}</el-text>
              <el-button
                size="small"
                type="danger"
                text
                :loading="deleting"
                @click="removeImage(image.filename)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useImageUpload } from '@/composables/use-image-upload';
import type { UploadFile, UploadUserFile } from 'element-plus';

const { uploading, deleting, uploadImage, deleteImage, getImageUrl } = useImageUpload();

const uploadRef = ref();
const fileList = ref<UploadUserFile[]>([]);
const uploadedImages = ref<{ filename: string; url: string }[]>([]);

const handleFileChange = async (file: UploadFile) => {
  if (!file.raw) return;

  const result = await uploadImage(file.raw);

  if (result) {
    uploadedImages.value.push({
      filename: result.filename,
      url: getImageUrl(result.filename)
    });

    // 清除文件列表
    uploadRef.value?.clearFiles();
    fileList.value = [];
  }
};

const removeImage = async (filename: string) => {
  const success = await deleteImage(filename);
  console.log(`尝试删除图片: ${filename}, 成功: ${success}`);
  if (success) {
    // 从列表中移除已删除的图片
    uploadedImages.value = uploadedImages.value.filter((img) => img.filename !== filename);

    // 确认删除成功的反馈
    console.log(`图片 ${filename} 已从服务器和列表中删除`);
  }
};
</script>

<style scoped>
.image-upload-demo {
  padding: 20px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.image-item {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
}

.uploaded-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.image-info {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
